<?php
/**
 * 用户注册控制器
 */
require_once 'config/config.php';
require_once 'includes/functions.php';
require_once 'classes/User.php';

// 如果用户已登录，重定向到首页
if (isLoggedIn()) {
    redirect(SITE_URL);
}

// 处理注册表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = sanitizeInput($_POST['username'] ?? '');
    $email = sanitizeInput($_POST['email'] ?? '');
    $phone = sanitizeInput($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirmPassword'] ?? '';
    $nickname = sanitizeInput($_POST['nickname'] ?? '');
    
    // 验证密码确认
    if ($password !== $confirmPassword) {
        $error = '两次输入的密码不一致';
    } else {
        $user = new User();
        $result = $user->register($username, $email, $phone, $password, $nickname);
        
        if ($result['status']) {
            setFlashMessage('success', $result['message']);
            redirect('login.php');
        } else {
            $error = $result['message'];
        }
    }
}

// 初始化变量
$username = $username ?? '';
$email = $email ?? '';
$phone = $phone ?? '';
$nickname = $nickname ?? '';
$error = $error ?? null;

// 加载视图
// 传递变量到视图
$pageTitle = '用户注册';
extract(compact('username', 'email', 'phone', 'nickname', 'error', 'pageTitle'));
require_once 'views/user/register.php';
